package my.http;

import android.text.TextUtils;
import android.util.Log;

import com.app.car.basis.Constants;

import java.io.IOException;

import my.LogUtil;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class MyInterceptor implements Interceptor {

    private final String tag = "HTTP";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        //通过拦截器添加header。
        Request.Builder builder = request.newBuilder();
//        if(LoginBean.isLogin()){
//            builder.addHeader("accToken", LoginBean.getInstance().getUserToken());
//        }
//        long time = new Date().getTime();
//        builder.addHeader("timestamp", time+"");
        Response response =  chain.proceed(builder.build());
        HttpUrl url = request.url();
        //http://127.0.0.1/test/upload/img?userName=xiaoming&userPassword=12345
        String scheme = url.scheme();//  http https
        String host = url.host();//   127.0.0.1
        String path = url.encodedPath();//  /test/upload/img
        String query = url.encodedQuery();//  userName=xiaoming&userPassword=12345
        RequestBody body = request.body();

        Headers headers = request.headers();
        if (headers != null && headers.size() > 0)
        {
            if(!TextUtils.isEmpty(headers.get(MyParams.PARAMS_LOG)) && headers.get(MyParams.PARAMS_LOG).equals("false")){
                LogUtil.i(tag, url.toString()+"  不打印log");
                return response;
            }
        }

//        LogUtil.i("intercept-->url-->"+url.toString());

        StringBuffer sb = new StringBuffer();
        if(TextUtils.isEmpty(scheme)){
//            String newUrl = sb.append(Constant).append(newHost).append(path).append("?").append(query).toString();
        }
        logForRequest(request);
        response =   logForResponse(response);

//        String bodyToString = requestBodyToString(body);
//        LogUtil.i(MyHttpUtils.tag,scheme);
//        LogUtil.i(MyHttpUtils.tag,host);
//        LogUtil.i(MyHttpUtils.tag,path);
//        LogUtil.i(MyHttpUtils.tag,query);
//        LogUtil.i(MyHttpUtils.tag,  body.toString());


        return response;
    }


    private Response logForResponse(Response response)
    {
        if(!Constants.DEBUG)return response;
        try
        {
            //===>response log
            Log.i(tag, "========response'log=======");
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            Log.i(tag, "url : " + clone.request().url());
            Log.i(tag, "code : " + clone.code());
            Log.i(tag, "protocol : " + clone.protocol());
            if (!TextUtils.isEmpty(clone.message()))
                Log.i(tag, "message : " + clone.message());

                ResponseBody body = clone.body();
                if (body != null)
                {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null)
                    {
                        Log.i(tag, "responseBody's contentType : " + mediaType.toString());
                        if (isText(mediaType))
                        {
                            String resp = body.string();
//                            Log.i(tag, "responseBody's content : " + resp);
                            LogUtil.i(tag, "responseBody's content : " + resp);

                            body = ResponseBody.create(mediaType, resp);
                            return response.newBuilder().body(body).build();
                        } else
                        {
                            Log.i(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
                        }
                    }

                }

            Log.i(tag, "========response'log=======end");
        } catch (Exception e)
        {
//            e.printStackTrace();
        }

        return response;
    }

    private void logForRequest(Request request)
    {

        if(!Constants.DEBUG)return;
        try
        {
            String url = request.url().toString();
            Headers headers = request.headers();

            Log.i(tag, "========request'log=======");
            Log.i(tag, "method : " + request.method());
            Log.i(tag, "url : " + url);
            if (headers != null && headers.size() > 0)
            {
                Log.i(tag, "headers : " + headers.toString());
                if(!TextUtils.isEmpty(headers.get(MyParams.PARAMS_LOG)) && headers.get(MyParams.PARAMS_LOG).equals("false")){
                    return;
                }
            }
            RequestBody requestBody = request.body();
            if (requestBody != null)
            {
                MediaType mediaType = requestBody.contentType();
                if (mediaType != null)
                {
                    Log.i(tag, "requestBody's contentType : " + mediaType.toString());
                    if (isText(mediaType))
                    {
                        LogUtil.i(tag, "requestBody's content : " + bodyToString(request));
                    } else
                    {
                        Log.i(tag, "requestBody's content : " + " maybe [file part] , too large too print , ignored!");
                    }
                }

                LogUtil.i(tag,"requestBody instanceof FormBody--->"+(requestBody instanceof FormBody));
                if (requestBody instanceof FormBody) {
                    StringBuilder sb = new StringBuilder();
                    FormBody body = (FormBody) requestBody;
                    for (int i = 0; i < body.size(); i++) {
                        sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                    }
                    sb.delete(sb.length() - 1, sb.length());
                    Log.i(tag, "| RequestParams:{"+sb.toString()+"}");
                }
            }
            Log.i(tag, "========request'log=======end");
        } catch (Exception e)
        {
//            e.printStackTrace();
        }
    }

    private boolean isText(MediaType mediaType)
    {
        if (mediaType.type() != null && mediaType.type().equals("text"))
        {
            return true;
        }
        if (mediaType.subtype() != null)
        {
            if (mediaType.subtype().equals("json") ||
                    mediaType.subtype().equals("xml") ||
                    mediaType.subtype().equals("html") ||
                    mediaType.subtype().equals("webviewhtml")
            )
                return true;
        }
        return false;
    }

    private String bodyToString(final Request request)
    {
        try
        {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e)
        {
            return "something error when show requestBody.";
        }
    }
}